package com.hgw.Demo07_FlyweightPattern.FlyweightPattern;

import com.hgw.Demo05_FacadePattern.examples.FileWriter;

import java.util.HashMap;

/**
 * Data time:2021/12/15 19:17
 * StudentID:2019112118
 * Author:hgw
 * Description: 享元工厂类
 */
public class FlyweightFactory {

    // 定义一个 HashMap 用于存储享元对象，实现享元池
    private HashMap flyweights = new HashMap();

    public Flyweight getFlyweights(String key) {
        // 如果对象存在，则直接从享元池获取
        if (flyweights.containsKey(key)) {
            return (Flyweight) flyweights.get(key);
        } else {
            // 如果对象不存在，先建立一个新的对象添加的享元池中，然后返回
            ConcreteFlyweight fw = new ConcreteFlyweight(key);
            flyweights.put(key, fw);
            return fw;
       }
    }
}
